import React, { useState, useEffect, useContext } from 'react'
import { Table, Modal } from 'antd'
import { LayoutContext } from '@/pages/layouts/context'

import './index.scss'

const ModalTable = (props) => {

  const {activePlan, setActivePlan, planInfos} = useContext(LayoutContext)
  const {visible, setVisible} = props
  const [choose, setChoose] = useState()
  const modalColumns = [
    { title: '序号', align: 'center', dataIndex: 'plan_id' },
    { title: '预案名称', align: 'center', dataIndex: 'plan_name' },
    { title: '起始时间', align: 'center', dataIndex: 'start_time' },
    { title: '终止时间', align: 'center', dataIndex: 'end_time' },
    { title: '预案级别', align: 'center', dataIndex: 'plan_level' },
    { title: '持续时间(天)', align: 'center', dataIndex: 'duration_days' },
    { title: '预案类别', align: 'center', dataIndex: 'plan_type' },
  ]

  const [modalDataSource, setModalDataSource] = useState([])

  useEffect(() => {
    if(!planInfos) return;
    let result = planInfos.map((i) => {
      return {key: i.plan_id,
        plan_id: i.plan_id,
        plan_type: i.plan_type,
        plan_name: i.plan_name,
        start_time: i.start_time,
        end_time: i.end_time,
        duration_days: i.duration_days,
        plan_level: i.plan_level
      }
    })
    setModalDataSource(result)
  }, [planInfos])

  return (
    <Modal
      title="列表"
      open={visible}
      style={{ top: '10%' }}
      width={'70%'}
      centered={false}
      onCancel={() => {
        setVisible(false)
      }}
      onOk={() => {
        setActivePlan(planInfos.find(item => item.plan_id === choose))
        setVisible(false)
      }}
    >
      <Table
        scroll={{y: 500}}
        size="small"
        pagination={false}
        className="modalTable"
        columns={modalColumns}
        dataSource={modalDataSource}
        rowSelection={{
          hideSelectAll: true,
          getCheckboxProps: (record) => {
            return {
              style: {
                display: 'none'
              }
            }
          },
          selectedRowKeys: [choose ? choose : activePlan ? activePlan.plan_id : undefined]
        }}
        onRow={(record) => {
          return {onClick: () => {
            setChoose(record.plan_id)
          }}
        }}
      />
    </Modal>
  )
}

export default ModalTable
